#include <cstring>
#include <iostream>

#include "Datagramm.h"

Datagramm::Datagramm() :
	m_int_size(sizeof(uint32_t)) {
}

Datagramm::~Datagramm() {
}

std::vector<std::string> & Datagramm::getStrings() {
	return m_strings;
}

void Datagramm::printStrings(int first_string, std::string prefix) const {
	int i = 0;
	std::vector<std::string>::const_iterator it = m_strings.begin();
	for (; it != m_strings.end(); ++it, ++i) {
		if (it - m_strings.begin() >= first_string) {
			std::cout << prefix << *it << std::endl;
		}
	}
}

void Datagramm::putInt32(char *char_pointer, uint32_t i) const {
	*(uint32_t*) char_pointer = i;
}

uint32_t Datagramm::getInt32(const char *char_pointer) const {
	return *(uint32_t*) char_pointer;
}

std::vector<char> Datagramm::getDatagramm() const {
	uint32_t global_length = 0;
	std::vector<std::string>::const_iterator it = m_strings.begin();
	for (; it != m_strings.end(); ++it) {
		global_length += it->size() + m_int_size;
	}

	std::vector<char> result;
	result.resize(global_length + m_int_size);
	putInt32(&result[0], global_length);

	uint32_t write_pointer = m_int_size;
	it = m_strings.begin();
	for (; it != m_strings.end(); ++it) {
		putInt32(&result[write_pointer], it->size());
		write_pointer += m_int_size;
		//result.assign(write_length, *it);
		//TODO: make it in right way
		memcpy(&result[write_pointer], it->c_str(), it->size());
		write_pointer += it->size();
	}

	return result;
}

void Datagramm::putDatagramm(const std::vector<char> & datagramm) {
	uint32_t global_length = getInt32(&datagramm[0]);
	uint32_t read_pointer = m_int_size;
	m_strings.clear();

	while (read_pointer < global_length) {
		uint32_t string_length = getInt32(&datagramm[read_pointer]);
		read_pointer += m_int_size;
		std::string string;
		string.assign(&datagramm[read_pointer], string_length);
		string += '\0';
		read_pointer += string_length;
		m_strings.push_back(string);
	}
}

